Imports System.IO

Public Class formmain

    ' Version information.
    Public g_szVersion As String = "2.0"

    ' The settings are stored here.
    Shared g_oSettings As CSettings

    ' Tells if the application can be exited.
    Private m_bAllowClose As Boolean = False

    ' Fires when the form is loading.
    Private Sub formmain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ' NOTE: This can be done from the properties of notify icon in the designer.
        ' But for clarity it's also set here so no one misses it.
        NotifyIcon1.ContextMenuStrip = ContextMenuStrip1

        ' Set the tool tip of the notify icon.
        NotifyIcon1.Text = NotifyIcon1.Text.Replace("<version>", g_szVersion)

        ' Set the title of this dialog.
        Me.Text = Me.Text.Replace("<version>", g_szVersion)

        ' Load settings. This method returns true, if the settings.xml can be found, 
        ' otherwise false. If found, the initial mode is minimized on tray.
        Dim b_loadedSettings As Boolean
        b_loadedSettings = LoadSettings()

        If (b_loadedSettings = True) Then
            MinimizeToTray()
        End If
        If (b_loadedSettings = False) Then
            RestoreFromTray()
        End If
       
    End Sub

    ' Fires when the form is closing.
    Private Sub formmain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        ' Always save the setting.
        SaveSettingsToXMLFile()

        ' If closing is not allowed, just minimize to tray and cancel the close opetaration.
        If Not m_bAllowClose Then

            ' Minimize to tray and cancel the close operation.
            MinimizeToTray()
            e.Cancel = True

        End If

    End Sub

    ' Systray icon double clicked.
    Private Sub NotifyIcon1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick

        ' Double click on trya icon. Show the form.
        RestoreFromTray()

    End Sub

    ' Minimize to tray.
    Private Sub MinimizeToTray()

        Me.Visible = False
        Me.ShowInTaskbar = False
        NotifyIcon1.Visible = True

    End Sub

    ' Restore from tray.
    Private Sub RestoreFromTray()

        NotifyIcon1.Visible = False
        Me.Visible = True
        Me.ShowInTaskbar = True

    End Sub

    ' Systray menu Settings clicked.
    Private Sub ToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem1.Click

        ' Settings clicked, so show the form.
        RestoreFromTray()

    End Sub

    ' Systray menu Exit clicked.
    Private Sub ToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem2.Click

        ' Ask confirmation.
        If (MsgBox("Are you sure you want to exit eCopy Connector for M-Files?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes) Then

            ' Allow closing and close this form when exited from context menu.
            m_bAllowClose = True
            Me.Close()

        End If

    End Sub

    ' Close button clicked.
    Private Sub btnMinimize_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMinimize.Click

        ' Close the dialog.
        Me.Close()

    End Sub

    ' Load settings. Returns false if the settings file cannot be used.
    Private Function LoadSettings() As Boolean

        ' Flag that tells the settings have been read successfully.
        Dim bSettingsReadSuccessfully As Boolean = False

        Try

            ' Check if the settings file exists.
            If (File.Exists("settings.xml") = True) Then

                ' Setting file exists, so read the values.

                ' Deserialize settings.xml.
                Dim fileStream As New System.IO.StreamReader("settings.xml")
                Dim oLoader As New System.Xml.Serialization.XmlSerializer(GetType(CSettings))
                g_oSettings = oLoader.Deserialize(fileStream)
                fileStream.Close()
                bSettingsReadSuccessfully = True

            End If

        Catch ex As Exception

            ' Show possible error message.
            MsgBox(ex.Message, MsgBoxStyle.Information)

        End Try

        ' If settings cannot be read successfully, create a new settings object here and 
        ' use default values.
        If (bSettingsReadSuccessfully = False) Then
            g_oSettings = New CSettings
        End If

        ' Set values to dialog.
        txtSourceFolder.Text = g_oSettings.SourceFolder
        txtShareScanProcessIdentifier.Text = g_oSettings.MainWindowTitleOfTheShareScanProcess

        ' Configure folder monitoring.
        ConfigureFolderMonitoring()

        ' Return.
        Return bSettingsReadSuccessfully

    End Function

    ' Save settings to the XML file from the dialog.
    Private Sub SaveSettingsToXMLFile()

        Try

            ' Get values from the dialog to the settings file.
            g_oSettings.MainWindowTitleOfTheShareScanProcess = txtShareScanProcessIdentifier.Text
            g_oSettings.SourceFolder = txtSourceFolder.Text

            ' Write values to the file.
            Dim fileStream As New System.IO.StreamWriter("settings.xml")
            Dim oLoader As New System.Xml.Serialization.XmlSerializer(GetType(CSettings))
            oLoader.Serialize(fileStream, g_oSettings)
            fileStream.Close()

        Catch ex As Exception

            ' Show possible error message.
            MsgBox(ex.Message, MsgBoxStyle.Information)

        End Try
      
    End Sub

    ' Source path edited.
    Private Sub txtSourceFolder_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSourceFolder.LostFocus

        ' Configure folder monitoring.
        ConfigureFolderMonitoring()

    End Sub

    ' Configure folder monitoring.
    Private Sub ConfigureFolderMonitoring()

        Try

            ' Validate the path.
            If (txtSourceFolder.Text.EndsWith("\") = False) Then
                txtSourceFolder.Text = txtSourceFolder.Text & "\"
            End If

            ' Configure folder watcher.
            fswSourceFolder.Path = txtSourceFolder.Text
            fswSourceFolder.Filter = "*.pdf"

        Catch ex As Exception

            ' Show possible error message.
            MsgBox(ex.Message, MsgBoxStyle.Information)

        End Try

    End Sub

    ' A new file created in the source folder.
    Private Sub fswSourceFolder_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles fswSourceFolder.Created

    End Sub

    Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click

        Dim form As formparent = New formparent
        form.Initialize("c:\temp\scan\koe.pdf")
        form.ShowDialog()
        ' Delete the source file.
        'System.IO.File.Delete(e.FullPath)

    End Sub

    Private Sub btnTest2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest2.Click

        ' Allow closing and close this form when exited from context menu.
        m_bAllowClose = True
        Me.Close()

    End Sub
End Class
